<template>
  <view class="page-container">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      title="标签管理" 
      :show-back="true"
      @rightClick="goToAddTag"
    >
      <template #right>
        <uni-icons type="plus" size="20" color="#333"></uni-icons>
      </template>
    </CustomNavBar>
    
    <!-- 页面内容 -->
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
      <scroll-view 
        scroll-y 
        class="tag-scroll"
        refresher-enabled
        :refresher-triggered="refreshing"
        @refresherrefresh="refreshData"
      >
        <!-- 搜索框 -->
        <view class="search-section margin-bottom-2">
          <view class="search-wrapper">
            <uni-icons type="search" size="18" color="#999"></uni-icons>
            <input
              v-model="searchKeyword"
              placeholder="搜索标签..."
              @input="handleSearch"
            />
          </view>
        </view>
        
        <!-- 标签云 -->
        <view class="tag-cloud-section margin-bottom-2" v-if="filteredTags.length > 0">
          <view class="section-title">
            <text class="title-text">标签云</text>
            <text class="title-count">{{ filteredTags.length }} 个标签</text>
          </view>
          <view class="tag-cloud">
            <view 
              class="tag-cloud-item" 
              v-for="tag in filteredTags" 
              :key="tag.id"
              :style="getTagCloudStyle(tag)"
              @click="editTag(tag)"
              @longpress="showTagMenu(tag)"
            >
              <text class="tag-name">{{ tag.name }}</text>
              <text class="tag-count">{{ tag.diaryCount || 0 }}</text>
            </view>
          </view>
        </view>
        
        <!-- 标签列表 -->
        <view class="tag-list-section">
          <view class="section-title">
            <text class="title-text">标签列表</text>
            <view class="sort-options">
              <text 
                class="sort-option" 
                :class="{ active: sortBy === 'name' }"
                @click="changeSortBy('name')"
              >
                按名称
              </text>
              <text 
                class="sort-option" 
                :class="{ active: sortBy === 'count' }"
                @click="changeSortBy('count')"
              >
                按使用次数
              </text>
              <text 
                class="sort-option" 
                :class="{ active: sortBy === 'time' }"
                @click="changeSortBy('time')"
              >
                按创建时间
              </text>
            </view>
          </view>
          
          <view class="tag-list">
            <view 
              class="tag-item card margin-bottom-1" 
              v-for="tag in sortedTags" 
              :key="tag.id"
              @click="editTag(tag)"
              @longpress="showTagMenu(tag)"
            >
              <view class="tag-content">
                <view class="tag-info">
                  <view class="tag-color" :style="{ backgroundColor: tag.color }"></view>
                  <view class="tag-details">
                    <text class="tag-name">{{ tag.name }}</text>
                    <text class="tag-meta">创建于 {{ formatDate(tag.createdAt) }}</text>
                  </view>
                </view>
                
                <view class="tag-stats">
                  <view class="stat-item">
                    <text class="stat-number">{{ tag.diaryCount || 0 }}</text>
                    <text class="stat-label">使用次数</text>
                  </view>
                  <uni-icons type="more" size="20" color="#ccc" @click.stop="showTagMenu(tag)"></uni-icons>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <EmptyState 
          v-if="tags.length === 0 && !loading" 
          type="tag" 
          title="暂无标签"
          description="创建你的第一个标签，让日记更有个性"
          button-text="创建标签"
          @buttonClick="goToAddTag"
        />
        
        <!-- 搜索无结果 -->
        <EmptyState 
          v-if="tags.length > 0 && filteredTags.length === 0 && searchKeyword"
          type="search" 
          title="未找到相关标签"
          :description="`没有找到包含'${searchKeyword}'的标签`"
          button-text="创建新标签"
          @buttonClick="goToAddTag"
        />
      </scroll-view>
    </view>
    
    <!-- 悬浮按钮 -->
    <view class="fab-container">
      <view class="fab-btn bg-primary" @click="goToAddTag">
        <uni-icons type="plus" size="24" color="#ffffff"></uni-icons>
      </view>
    </view>
    
    <!-- 标签操作菜单 -->
    <TagActionModal
      v-model:show="showActionModal"
      :tag="selectedTag"
      @edit="editTag"
      @delete="deleteTag"
      @viewDiaries="viewTagDiaries"
    />
    
    <!-- 加载组件 -->
    <LoadingComponent :visible="loading" text="加载中..." />
  </view>
</template>

<script>
import { useDiaryStore } from '@/store/diary'
import { useUserStore } from '@/store/user'
import { getTagsAPI, deleteTagAPI } from '@/api/tag'
import { formatDate } from '@/utils/index'
import CustomNavBar from '@/components/CustomNavBar.vue'
import EmptyState from '@/components/EmptyState.vue'
import LoadingComponent from '@/components/LoadingComponent.vue'
import TagActionModal from '@/components/TagActionModal.vue'

export default {
  name: 'TagListPage',
  components: {
    CustomNavBar,
    EmptyState,
    LoadingComponent,
    TagActionModal
  },
  setup() {
    const diaryStore = useDiaryStore()
    const userStore = useUserStore()
    
    return {
      diaryStore,
      userStore,
      formatDate
    }
  },
  data() {
    return {
      navBarHeight: 88,
      tags: [],
      loading: false,
      refreshing: false,
      searchKeyword: '',
      sortBy: 'count', // name, count, time
      showActionModal: false,
      selectedTag: null
    }
  },
  computed: {
    filteredTags() {
      let filtered = this.tags
      
      if (this.searchKeyword) {
        filtered = filtered.filter(tag => 
          tag.name.toLowerCase().includes(this.searchKeyword.toLowerCase())
        )
      }
      
      return filtered
    },
    
    sortedTags() {
      const tags = [...this.filteredTags]
      
      switch (this.sortBy) {
        case 'name':
          return tags.sort((a, b) => a.name.localeCompare(b.name))
        case 'count':
          return tags.sort((a, b) => (b.diaryCount || 0) - (a.diaryCount || 0))
        case 'time':
          return tags.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
        default:
          return tags
      }
    }
  },
  onLoad() {
    this.initPage()
  },
  onShow() {
    this.loadTags()
  },
  onPullDownRefresh() {
    this.refreshData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    async initPage() {
      // 检查登录状态
      if (!this.userStore.checkLoginStatus()) return
      
      // 获取导航栏高度
      const systemInfo = uni.getSystemInfoSync()
      this.navBarHeight = systemInfo.statusBarHeight + 44
      
      // 加载标签列表
      await this.loadTags()
    },
    
    async loadTags() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const res = await getTagsAPI()
        this.tags = res.data || []
        
        // 更新状态管理中的标签数据
        this.diaryStore.setTags(this.tags)
        
      } catch (error) {
        console.error('加载标签失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async refreshData() {
      this.refreshing = true
      await this.loadTags()
      this.refreshing = false
    },
    
    // 搜索处理
    handleSearch() {
      // 实时搜索，无需额外处理
    },
    
    // 排序切换
    changeSortBy(sortBy) {
      this.sortBy = sortBy
    },
    
    // 获取标签云样式
    getTagCloudStyle(tag) {
      const count = tag.diaryCount || 0
      const maxCount = Math.max(...this.filteredTags.map(t => t.diaryCount || 0))
      const minSize = 24
      const maxSize = 40
      const size = minSize + (maxSize - minSize) * (count / maxCount || 0)
      
      return {
        fontSize: `${size}rpx`,
        backgroundColor: tag.color + '20',
        color: tag.color,
        border: `2rpx solid ${tag.color}40`
      }
    },
    
    // 显示标签操作菜单
    showTagMenu(tag) {
      this.selectedTag = tag
      this.showActionModal = true
    },
    
    // 创建标签
    goToAddTag() {
      uni.navigateTo({
        url: '/pages/tag/edit'
      })
    },
    
    // 编辑标签
    editTag(tag) {
      uni.navigateTo({
        url: `/pages/tag/edit?id=${tag.id}`
      })
      this.showActionModal = false
    },
    
    // 删除标签
    async deleteTag(tag) {
      try {
        const result = await uni.showModal({
          title: '确认删除',
          content: `确定要删除标签"${tag.name}"吗？\n删除后该标签将从所有日记中移除。`,
          showCancel: true,
          confirmColor: '#ff4d4f'
        })
        
        if (!result.confirm) return
        
        this.loading = true
        
        await deleteTagAPI(tag.id)
        
        // 从列表中移除
        const index = this.tags.findIndex(t => t.id === tag.id)
        if (index > -1) {
          this.tags.splice(index, 1)
        }
        
        // 更新状态管理
        this.diaryStore.setTags(this.tags)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('删除标签失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.showActionModal = false
      }
    },
    
    // 查看标签下的日记
    viewTagDiaries(tag) {
      // 设置筛选条件并跳转到日记列表
      this.diaryStore.setFilters({ tagIds: [tag.id] })
      
      uni.navigateTo({
        url: '/pages/diary/list'
      })
      
      this.showActionModal = false
    }
  }
}
</script>

<style scoped>
.tag-scroll {
  height: calc(100vh - 88px);
  padding-bottom: 120rpx;
}

.search-section {
  padding: 0 32rpx;
}

.search-wrapper {
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 32rpx;
  padding: 20rpx 32rpx;
  height: 72rpx;
}

.search-wrapper input {
  flex: 1;
  font-size: 28rpx;
  margin-left: 16rpx;
  background-color: transparent;
  border: none;
}

.tag-cloud-section {
  padding: 0 32rpx;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.title-count {
  font-size: 24rpx;
  color: #999999;
}

.sort-options {
  display: flex;
  gap: 24rpx;
}

.sort-option {
  font-size: 24rpx;
  color: #666666;
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  background-color: #f8f8f8;
  transition: all 0.3s;
}

.sort-option.active {
  background-color: #1890ff;
  color: #ffffff;
}

.tag-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  padding: 24rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.tag-cloud-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
  transition: all 0.3s;
}

.tag-cloud-item:active {
  transform: scale(0.95);
}

.tag-name {
  font-weight: 500;
}

.tag-count {
  font-size: 20rpx;
  opacity: 0.8;
}

.tag-list-section {
  padding: 0 32rpx;
}

.tag-list {
  margin-top: 24rpx;
}

.tag-item {
  padding: 32rpx;
  transition: transform 0.2s;
}

.tag-item:active {
  transform: scale(0.98);
}

.tag-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tag-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.tag-color {
  width: 24rpx;
  height: 24rpx;
  border-radius: 12rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.tag-details {
  flex: 1;
  min-width: 0;
}

.tag-item .tag-name {
  display: block;
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 8rpx;
}

.tag-meta {
  font-size: 24rpx;
  color: #999999;
}

.tag-stats {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: 20rpx;
  color: #999999;
}

.fab-container {
  position: fixed;
  bottom: 120rpx;
  right: 32rpx;
  z-index: 100;
}

.fab-btn {
  width: 112rpx;
  height: 112rpx;
  border-radius: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.3);
}
</style> 